package com.miaomiao.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miaomiao.common.Result;
import com.miaomiao.domain.system.RegisterBody;
import com.miaomiao.domain.system.User;
import com.miaomiao.service.system.ResetService;
import com.miaomiao.service.system.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/reset")
@Api(tags = "重置密码")
public class ResetController {

    @Autowired
    public ResetService resetService;

    @Autowired
    public UserService userService;

    @GetMapping("/checkUserName")
    @ApiOperation("检查用户名是否可用")
    public Result checkUserName(@RequestParam String userName){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User user = userService.getOne(queryWrapper);
        if(Objects.isNull(user)){
            return Result.error("用户名不存在");
        }else{
            return Result.success("用户名正确");
        }
    }

    @GetMapping("/checkEmail")
    @ApiOperation("检查邮箱是否正确")
    public Result checkEmail(@RequestParam String userName,String email){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User user = userService.getOne(queryWrapper);
        if(Objects.isNull(user)){
            return Result.error("用户名不存在");
        }else{
            if(Strings.isEmpty(email) || !email.equals(user.getEmail())){
                return Result.error("邮箱与该用户注册时的邮箱不一致！");
            }else{
                return Result.success("邮箱正确");
            }
        }
    }

    @GetMapping("/sendCode")
    @ApiOperation("发送邮箱验证码")
    public Result sendCode(@RequestParam String email){
        return resetService.senCode(email);
    }

    @PostMapping
    @ApiOperation("重置密码")
    public Result resetPassword(@RequestBody RegisterBody registerBody){
        return resetService.resetPassword(registerBody);
    }
}
